<template>
  <div class="main-page">
    <div class="main-01">
      <div class="main-tab-01-01">
        <div class="main-tab-title">
          <span>今日幼儿出勤</span>
        </div>
        <div id="attendanceChart" style="width: 100%; height: 400px;"></div>
        <div class="main-content line-01-bottom">
          <p><span>应到：{{ total }} </span></p>
          <p><span>实到：{{ actual }} </span> <span>占比：{{ actualPercent }}%</span></p>
          <p><span>事假：{{ leave }} </span> <span>占比：{{ leavePercent }}%</span></p>
          <p><span>病假：{{ sick }} </span> <span>占比：{{ sickPercent }}%</span></p>
        </div>
      </div>
      <div class="main-tab-01-01">
        <div class="main-tab-title">
          <span>各班出勤率</span>
        </div>
        <table class="attendance-table">
          <thead>
          <tr>
            <th>班级</th>
            <th>总人数</th>
            <th>签到人数</th>
            <th>出勤率</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="cls in classes" :key="cls.id">
            <td>{{ cls.class_name }}</td>
            <td>{{ cls.number }}</td>
            <td>{{ cls.sign }}</td>
            <td>{{ (cls.sign / cls.number * 100).toFixed(2) }}%</td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div class="main-02">
      <div class="main-02-top">
        <div class="main-tab-title" style="margin-bottom: 0">
          <span>全校发育数据总览</span>
        </div>
        <div style="width:100%" class="year_Chart">
          <developmentTable :data="developmentData"></developmentTable>
        </div>
      </div>
      <div class="main-02-bottom">
        <div class="main-02-bottom-l">
          <div class="main-tab-title">
            <span>今日晨检</span>
          </div>
          <div class="main-content line-02-bottom">
            <p><span>应检：{{ actual }} 人</span> <span>已检：{{ actual }} 人</span></p>
            <p><span>异常：{{ totalAbnormal }} 人</span> <span>占比：{{ ((totalAbnormal / actual) * 100).toFixed(2) }}%</span>
            </p>
            <p><span>正常：{{ actual - totalAbnormal }} 人</span>
              <span>占比：{{ (((actual - totalAbnormal) / actual) * 100).toFixed(2) }}%</span></p>
          </div>
          <div id="morning_Chart" style="width:100%;height: 550px;" class="morning_Chart"></div>
        </div>
        <div class="main-02-bottom-l">
          <div class="main-02-bottom-l-01">
            <div class="main-tab-title">
              <span>流行病统计表</span>
            </div>
            <div id="epidemic_Chart" style="width:100%;height: 400px;" class="epidemic_Chart"></div>
          </div>

          <div class="main-02-bottom-l-02">
            <div class="main-tab-title">
              <span>家长留言</span>
            </div>
            <div class="home_top_Development">
              <div class="comments-container">
                <div v-for="comment in parentComments" :key="comment.id" class="comment-item">
                  <p><strong>{{ comment.class }}</strong><strong>{{ comment.name }}</strong> {{ comment.message }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="main-03">
      <div class="main-tab-01-01">
        <div class="main-tab-title">
          <span>病假分布</span>
        </div>
        <div id="disease_Chart" style="width:100%;height:450px;" class="disease_Chart"></div>
      </div>
      <div class="main-tab-01-01">
        <div class="main-tab-title">
          <span>光盘行动</span>
        </div>
        <div class="main-content">
          <p>应到人数：{{ totalPeople }} 光盘人数：{{ clearedPeople }} 未光盘人数：{{ totalPeople - clearedPeople }}</p>
        </div>
        <div id="clear_Chart" style="width:100%;height: 450px;" class="clear_Chart"></div>
      </div>
    </div>
  </div>
</template>


<script>
import {nurseryDashboard} from "@/api/admin/school";

let echarts = require('echarts');
import developmentTable from "@/fullscreen/components/developmentTable";

export default {
  name: "home",
  components: {developmentTable},
  data() {
    return {
      parentComments: [],
      developmentData: [],
      total: 0,
      actual: 0,
      leave: 0,
      sick: 0,
      sickPercent: 0,
      actualPercent: 0,
      leavePercent: 0,
      totalAttendance: 0,
      totalInspected: 100,
      actualInspected: 90,
      normalCount: 0,
      normalPercentage: 0,
      sickCount: 10,
      sickPercentage: 11.11,
      classes: [],
      totalPeople: 0,
      totalAbnormal: 0,
      clearedPeople: 0,
      morningChartData: {
        categories: ['应检人数', '实检人数', '正常', '正常缠臂', '异常', '异常占比'],
        series: [100, 90, 80, 70, 10, 10]
      },
      attendanceChartData: {
        categories: ['指甲长', '指甲脏', '流鼻涕', '其他'],
        series: [20, 15, 10, 5]
      }
    };
  },
  computed: {
    totalClasses() {
      return this.classes.reduce((acc, cls) => acc + cls.number, 0);
    },
    totalSign() {
      return this.classes.reduce((acc, cls) => acc + cls.sign, 0);
    },
    totalAttendanceRate() {
      const total = this.totalClasses;
      const sign = this.totalSign;
      return total > 0 ? ((sign / total) * 100).toFixed(2) : 0;
    }
  },
  created() {
    this.getSchoolFn();
    this.getDevelopmentData();
  },
  mounted() {
  },
  methods: {
    async getDevelopmentData() {
      try {
        let data = await this.$post(this.api.Developmental.data.index, {});
        console.log('Development data:', data);
        if (data) {
          this.developmentData = this.transformData(data.data);
        }
      } catch (error) {
        console.error('Error fetching development data:', error);
      }
    },
    transformData(data) {
      return data.map((item,index) => ({
        age: `${index}岁-`,
        student_number: item.student_number,
        growth_number: item.growth_number,
        height1: item.height1,
        weight1: item.weight1,
        height_rebate1: item.height_rebate1,
        weight_rebate1: item.weight_rebate1,
        height2: item.height2,
        weight2: item.weight2,
        height_rebate2: item.height_rebate2,
        weight_rebate2: item.weight_rebate2,
        height3: item.height3,
        weight3: item.weight3,
        height_rebate3: item.height_rebate3,
        weight_rebate3: item.weight_rebate3,
        height4: item.height4,
        weight4: item.weight4,
        height_rebate4: item.height_rebate4,
        weight_rebate4: item.weight_rebate4,
        height5: item.height5,
        weight5: item.weight5,
        height_rebate5: item.height_rebate5,
        weight_rebate5: item.weight_rebate5,
        height6: item.height6,
        weight6: item.weight6,
        height_rebate6: item.height_rebate6,
        weight_rebate6: item.weight_rebate6
      }));
    },
    // 今日出勤
    attendance_echarts(data) {
      this.$nextTick(function () {
        // 基于准备好的dom，初始化echarts实例
        const chartDom = document.getElementById('attendanceChart');
        const myChart = echarts.init(chartDom);

        // 计算总人数
        // const total = data.reduce((acc, item) => acc + item.number, 0);
        // this.total = total;

        // 计算各部分人数
        const total = data.find(item => item.name === '应到')?.number || 0;
        const actual = data.find(item => item.name === '实到')?.number || 0;
        const leave = data.find(item => item.name === '事假')?.number || 0;
        const sick = data.find(item => item.name === '病假')?.number || 0;

        // 计算应到人数
        this.totalAttendance = total - (actual + leave + sick);

        // 计算各部分占比
        this.actualPercent = ((actual / total) * 100).toFixed(2);
        this.leavePercent = ((leave / total) * 100).toFixed(2);
        this.sickPercent = ((sick / total) * 100).toFixed(2);

        // 更新数据
        this.total = total;
        this.actual = actual;
        this.leave = leave;
        this.sick = sick;
        let data_ = JSON.parse(JSON.stringify(data))
        let index_ = 'all'
        for (let index in data_) {
          let item = data_[index]
          if (item.name == '应到') {
            index_ = index
          }
        }
        delete data_[index_]
        // 计算百分比
        const seriesData = data_.map(item => ({
          name: item.name,
          value: item.number,
          percent: ((item.number / total) * 100).toFixed(2)
        }));

        // 指定图表的配置项和数据
        const option = {
          title: {
            show: false,
            text: '今日幼儿出勤情况',
            left: 'center',
            textStyle: {
              color: '#fff' // 标题文字颜色
            }
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            textStyle: {
              color: '#fff' // 图例文字颜色
            }
          },
          series: [
            {
              name: '出勤情况',
              type: 'pie',
              radius: ['50%', '70%'], // 内外圆环的半径
              itemStyle: {
                borderColor: '#fff', // 圆环边框颜色
                borderWidth: 2 // 圆环边框宽度
              },
              avoidLabelOverlap: false,
              label: {
                show: true,
                position: 'outside',
                formatter: function (params) {
                  return `${params.name}: ${params.value} (${params.percent}%)`;
                },
                color: '#fff' // 标签文字颜色
              },
              labelLine: {
                show: true,
                length: 15, // 标签线长度
                length2: 10, // 标签线第二段长度
                lineStyle: {
                  color: '#fff' // 标签线颜色
                }
              },
              data: seriesData
            }
          ]
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
      });
    },
    // 今日晨检
    morning_echarts(data) {
      this.$nextTick(() => {
        const morningChart = echarts.init(document.getElementById('morning_Chart'));

        // 计算异常总人数
        this.totalAbnormal = data.reduce((sum, item) => sum + item.number, 0);
        this.normalCount = this.totalAttendance - this.totalAbnormal;
        this.normalPercentage = ((this.normalCount / this.totalAttendance) * 100).toFixed(2);

        const option = {
          title: {
            show: false,
            text: '人数'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function (params) {
              if (params.length > 0) {
                const param = params[0];
                return `${param.name}: ${param.value}人`;
              }
              return '';
            }
          },
          xAxis: {
            type: 'value',
            name: '人数',
            max: 50, // 调整最大值以适应数据
            axisLine: {
              lineStyle: {
                color: '#b5c5d4', // 颜色
              }
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: '#315070',
                type: 'dashed'
              }
            },
          },
          yAxis: {
            type: 'category',
            data: data.map(item => item.name),
            axisLabel: {
              color: '#b5c5d4' // 文字颜色改为白色
            }
          },
          series: [
            {
              name: '数量',
              type: 'bar',
              data: data.map(item => item.number),
              itemStyle: {
                color: function (params) {
                  const colorList = ['#bcc359', '#39add1', '#8c7bc6', '#f16936', '#6cddfc', '#f6cc48', '#51bbac', '#bb2300', '#708cdf', '#de567c'];
                  return colorList[params.dataIndex % colorList.length];
                }
              }
            }
          ]
        };

        // 设置图表选项
        morningChart.setOption(option);
      });
    },


    // 流行病统计表
    initEpidemicEcharts(data) {
      this.$nextTick(() => {
        const epidemicChart = echarts.init(document.getElementById('epidemic_Chart'));

        const dates = data.map(item => {
          const start = new Date(item.start_time * 1000).toLocaleDateString();
          const end = new Date(item.end_time * 1000).toLocaleDateString();
          return `${start} 至 ${end}`;
        });

        const diseases = data[0].disease.map(d => d.name);

        const seriesData = diseases.map(diseaseName => {
          return {
            name: diseaseName,
            type: 'bar',
            stack: '总量',
            data: data.map(week => week.disease.find(d => d.name === diseaseName)?.number || 0)
          };
        });

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: diseases,
            textStyle: {
              color: '#FFFFFF' // 文字颜色改为白色
            }
          },
          xAxis: {
            type: 'category',
            data: dates,
            axisLabel: {
              color: '#b5c5d4' // 文字颜色改为白色
            }
          },
          yAxis: {
            name: '人数',
            type: 'value',
            max: 50, // 调整最大值以适应数据
            axisLine: {
              lineStyle: {
                color: '#b5c5d4', // 颜色
              }
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: '#315070',
                type: 'dashed'
              }
            },
          },
          series: seriesData
        };

        epidemicChart.setOption(option);
      });
    },
    // 病假分布
    initDiseaseEcharts(data) {
      console.log(data, '病假分布');
      const diseaseChart = echarts.init(document.getElementById('disease_Chart'));

      // 计算总数
      const total = data.reduce((sum, item) => sum + item.number, 0);

      // 计算每个类别的占比
      const seriesData = data.map(item => ({
        name: item.name,
        value: item.number,
        percent: total > 0 ? ((item.number / total) * 100).toFixed(2) : 0
      }));

      const option = {
        color: ['#C1232B', '#B5C334', '#FCCE10', '#E87C25', '#27727B', '#FE8463', '#9BCA63', '#FAD860'],
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            return `${params.name}: ${params.value} (${params.percent}%)`;
          }
        },
        legend: {
          orient: 'horizontal',
          left: 'top',
          data: seriesData.map(item => item.name),
          formatter: (name) => {
            return `${name}`;
          },
          textStyle: {
            color: '#FFFFFF' // 文字颜色改为白色
          }
        },
        label: {
          show: true,
          position: 'outside',
          formatter: function (params) {
            return `${params.name}: ${params.value} (${params.percent}%)`;
          },
          color: '#fff' // 标签文字颜色
        },
        series: [
          {
            name: '病假分布',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: seriesData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      diseaseChart.setOption(option);
    },
    // 光盘数据
    calculateStatistics(data) {
      let total = 0;
      let cleared = 0;

      data.forEach(item => {
        total += item.number;
        if (item.name === "剩余10%以下") {
          cleared += item.number;
        }
      });

      this.totalPeople = total;
      this.clearedPeople = cleared;
    },
    initClearEcharts(data) {
      const chartDom = document.getElementById('clear_Chart');
      const myChart = echarts.init(chartDom);

      const seriesData = data.map(item => ({
        name: item.name,
        value: item.number
      }));

      const option = {
        color: ['#C1232B', '#B5C334', '#FCCE10', '#E87C25', '#27727B', '#FE8463', '#9BCA63', '#FAD860'],
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            return `${params.name}: ${params.value} (${params.percent}%)`;
          }
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: seriesData.map(item => item.name),
          formatter: (name) => {
            const item = seriesData.find(item => item.name === name);
            console.log('item++++++', item)
            let number_ = ''
            if (item.value) {
              number_ = `${name}: ${item.value} (${this.total}%)`
            } else {
              number_ = `${name}: ${item.value} (0%)`
            }
            return number_;
          },
          textStyle: {
            color: '#fff'
          }
        },
        series: [
          {
            name: '光盘情况',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: seriesData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      myChart.setOption(option);
    },
    getSchoolFn() {
      nurseryDashboard().then(res => {
        if (res.code == 0) {
          this.attendance_echarts(res.sign);
          this.morning_echarts(res.morning);
          this.initEpidemicEcharts(res.week);
          this.initDiseaseEcharts(res.now_disease);
          this.calculateStatistics(res.clear);
          this.initClearEcharts(res.clear);
          this.classes = res.class;
          this.parentComments = res.messgae.map(item => ({
            class: item.classes.class_name,
            name: item.student.name,
            message: item.content
          }));
        }
        console.log(res, '保育返回的');
      });
    }
  }
}
</script>

<style scoped>
.main-page {
  display: flex;
  padding: 10px;
}

.main-tab-title {
  background: url(./assets/img/h-008.png) no-repeat;
  background-size: 100% 50px;
  background-position: left bottom;
  height: 50px;
  font-style: italic;
  font-size: 26px;
  padding-left: 40px;
  line-height: 24px;
  font-weight: 500;
  margin-bottom: 20px;
}

.main-tab-title span {
  background: linear-gradient(to bottom, #fff, #fcfcb8);
  -webkit-background-clip: text; /* 将背景裁剪为文字区域 */
  -webkit-text-fill-color: transparent; /* 将文字颜色设置为透明 */
  /*color: #fcfcb8;*/
  /*text-shadow: 2px 2px 1px #000;*/
}

.main-content {
  font-size: 18px;
  color: #fff;
}

.main-01 {
  width: 20%;
  background: rgba(5, 25, 53, .6);
  border-radius: 10px;
  padding: 10px;
  display: flex;
  flex-direction: column;
}

.main-02 {
  flex: 1;
  background: rgba(5, 25, 53, .6);
  margin: 0 20px;
  border-radius: 10px;
}

.main-03 {
  width: 20%;
  background: rgba(5, 25, 53, .6);
  border-radius: 10px;
  padding: 10px;
}

.main-tab-box-t-01 span:nth-child(1) {
  font-size: 14px;
  color: #ddd;
  margin-bottom: 5px;
  display: block;
}

.main-tab-box-t-01 span:nth-child(2) {
  font-size: 20px;
}

.home_top_Development {
  height: 100%;
  width: 100%;
}

.main-tab-01-01 {
  flex: 1; /* 使每个子元素高度相等 */
  display: flex;
  flex-direction: column;
  margin-bottom: 30px;
}


.main-02-bottom {
  display: flex;
  /*align-items: center;*/
  padding-top: 20px;
}

.main-02-bottom-l {
  flex: 1;
}

.main-02-bottom-l:first-child {
  margin-right: 20px;
}

.attendance-table {
  width: 100%;
  border-collapse: collapse;
}

.attendance-table th,
.attendance-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center; /* 居中对齐 */
  color: white; /* 字体颜色为白色 */
}

.attendance-table th {
  background-color: #333; /* 表头背景颜色 */
}

.attendance-table td {
  color: #52ffff;
}

.main-02-bottom-l {
  display: flex;
  flex-direction: column;
  gap: 16px; /* 间距 */
  width: 100%; /* 确保容器宽度占满父元素 */
  max-width: 100%; /* 防止内容溢出 */
  box-sizing: border-box; /* 确保内边距和边框不会影响总宽度 */
}

.comment-item {
  margin-bottom: 12px;
}

.comment-item p {
  margin: 0;
  font-size: 16px;
  height: 36px;
  color: #fff;
}

.comment-item p strong {
  margin: 20px;

}

.banner-box img {
  width: 100%;
  display: block;
}

.line-01-bottom p {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.line-01-bottom p span {
  display: block;
}

.line-01-bottom p span:first-child {
  width: 100px;
}

.line-02-bottom p {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.line-02-bottom p span {
  display: block;
}

.line-02-bottom p span:first-child {
  width: 160px;
}
.comments-container {
  width: 100%; /* 根据需要调整宽度 */
  overflow-x: hidden; /* 水平滚动条 */
}

.comment-item {
  white-space: nowrap; /* 不换行 */
  overflow-x: hidden; /* 隐藏超出部分，防止内容被截断 */
  padding: 10px; /* 根据需要调整内边距 */
  border-bottom: 1px solid #ccc; /* 分隔线，可选 */
}

.comment {
  display: inline-block; /* 确保内容在同一行显示 */
}
.main-page {
  overflow-x: hidden;
}
.main-02-top {
  padding: 10px;
}
</style>
